﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.MaterialInfoCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.MaterialInfoHandler
{
    /// <summary>
    /// 物料信息查询命令处理
    /// </summary>
    public class MaterialInfoQueryCommandHandler : IRequestHandler<MaterialInfoQueryCommand, APIResult<APIPaing<MaterialInfo>>>
    {
        /// <summary>
        /// 物料信息仓储
        /// </summary>
        private readonly IBaseRepository<MaterialInfo> materialRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="materialRepository">物料信息仓储</param>
        /// <param name="mapper">映射</param>
        public MaterialInfoQueryCommandHandler(IBaseRepository<MaterialInfo> materialRepository,IMapper mapper)
        {
            this.materialRepository = materialRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public Task<APIResult<APIPaing<MaterialInfo>>> Handle(MaterialInfoQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaing<MaterialInfo>> result = new APIResult<APIPaing<MaterialInfo>>();
                result.Code = APIEnums.查询成功;
                result.Msg = APIEnums.查询成功.ToString();
                var list = materialRepository.GetAll().Result;
                var count = list.Count();
                var page = (int)Math.Ceiling(count * 1.0 / request.PageSize);
                var models = list.OrderByDescending(x => x.MaterialInfoId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                APIPaing<MaterialInfo> paging = new APIPaing<MaterialInfo>();
                paging.PageCount = page;
                paging.TotalCount = count;
                paging.Items = mapper.Map<List<MaterialInfo>>(models);
                result.data = paging;
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
